<?php


namespace App\Crontab;


use App\Model\CacheTable;
use App\Model\DataTable;
use App\Model\User;
use App\Model\Wechat;
use App\Utility\FinanceUtil;
use App\Utility\Pool\MysqlPool;
use App\Utility\Queue\Queue;
use App\Utility\Queue\QueueType;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Queue\Job;
use EasySwoole\WeChat\Bean\OfficialAccount\TemplateMsg;

class MessageTask extends AbstractCronTask
{


    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        // 定时周期 （每天一次早上10点）
        return '30 10 * * *';

    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'MessageTask';
    }


    function run(int $taskId, int $workerIndex)
    {
        // TODO: Implement run() method.
        echo('send' . self::getTaskName() . PHP_EOL);
        TaskManager::getInstance()->async(function () {
            //MessageTask::setTestJob();
            MessageTask::mytask();
        });

    }

    function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        // TODO: Implement onException() method.
        echo $throwable->getMessage();
    }


    public static function mytask()
    {
        if (FinanceUtil::isHoliday()) {
            return false;
        }
        $week = date("w");
        $db = MysqlPool::defer();
        if ($week != 6) {
            //查有多小人
            $user_count = $db
                ->join(DataTable::USER_TABLE . ' as u', 'u.id = t.user_id')
                ->where('t.is_follow', 1)
                ->where('u.status', 'normal')
                ->count(DataTable::THIRD_TABLE . ' as t');
            $page_size = QueueType::MESSAGE_SEND_COUNT;
            $pages = (int)$user_count / $page_size;
            if ($pages < 1) {
                $userlist = self::getUser($db, null);
                self::setMsgJob($db, $userlist);
                /*
                if(!in_array($week,[0,6])){
                    //昨天有竞猜过 今天未竞猜的弹出提示
                    self::setMsgJob($db,$userlist);
                    //self::setAllJob($db,$userlist);
                }else {
                    //周日提示 上周竞猜过 这周没竞猜过的
                    self::setMsg2Job($db,$userlist);
                    self::setMsg4Job($db,$userlist);
                }*/
            } else {
                for ($page = 0; $page < $pages - 1; $page++) {
                    $userlist = self::getUser($db, [($page * $page_size), (($page + 1) * $page_size)]);
                    self::setMsgJob($db, $userlist);
                    /*
                    if(!in_array($week,[0,6])){
                        //昨天有竞猜过 今天未竞猜的弹出提示
                        self::setMsgJob($db,$userlist);
                        //self::setAllJob($db,$userlist);
                    }else {
                        //周日提示 上周竞猜过 这周没竞猜过的
                        self::setMsg2Job($db,$userlist);
                        self::setMsg4Job($db,$userlist);
                    }*/
                }
                //取余数
                $mod = $user_count % $page_size;
                if ($mod > 0) {
                    $userlist = self::getUser($db, [($pages * $page_size), $user_count]);
                    if (count($userlist) > 0) {
                        self::setMsgJob($db, $userlist);
                        /**
                         * if(!in_array($week,[0,6])){
                         * //昨天有竞猜过 今天未竞猜的弹出提示
                         * self::setMsgJob($db,$userlist);
                         * //self::setAllJob($db,$userlist);
                         * }else {
                         * //周日提示 上周竞猜过 这周没竞猜过的
                         * self::setMsg2Job($db,$userlist);
                         * self::setMsg4Job($db,$userlist);
                         * }*/
                    }
                }
            }
        }

        //周六提示 新用户还没参加过竞猜的
        /**
         * if($week == 6){
         * $now = time();
         * $lastweek = time() - 604800;
         * // TODO: Implement run() method.
         * $db = MysqlPool::defer();
         * //查有多小人
         * $user_count = $db
         * ->join(DataTable::USER_TABLE.' as u','u.id = t.user_id')
         * ->whereBetween('t.createtime',[$lastweek,$now])
         * ->where('t.is_follow',1)
         * ->where('u.status','normal')
         * ->count(DataTable::THIRD_TABLE.' as t');
         * $page_size = QueueType::MESSAGE_SEND_COUNT;
         * $pages = (int)$user_count/$page_size;
         * if($pages < 1){
         * $userlist = self::getNewUser($db,[0,$user_count]);
         * self::setMsg3Job($db,$userlist);
         * }else{
         * for ($page=0;$page < $pages-1; $page++) {
         * $userlist = self::getNewUser($db,[($page*$page_size),(($page+1)*$page_size)-1]);
         * self::setMsg3Job($db,$userlist);
         * }
         * //取余数
         * $mod = $user_count%$page_size;
         * if($mod > 0){
         * $userlist = self::getNewUser($db,[($pages*$page_size),$user_count]);
         * self::setMsg3Job($db,$userlist);
         * }
         * }
         * }*/

    }

    private static function getUser($db, $limit)
    {
        $templist = $db
            ->join(DataTable::USER_TABLE . ' as u', 'u.id = t.user_id')
            ->where('t.is_follow', 1)
            ->where('u.status', 'normal')
            ->get(DataTable::THIRD_TABLE . ' as t', $limit, 't.user_id');
        $userlist = array();
        if (count($templist) > 0) {
            foreach ($templist as $user) {
                array_push($userlist, $user['user_id']);
            }
        }
        return $userlist;
    }

    private static function getNewUser($db, $limit)
    {
        $now = time();
        $lastweek = time() - 604800;
        $templist = $db
            ->join(DataTable::USER_TABLE . ' as u', 'u.id = t.user_id')
            ->whereBetween('t.createtime', [$lastweek, $now])
            ->where('t.is_follow', 1)
            ->where('u.status', 'normal')
            ->get(DataTable::THIRD_TABLE . ' as t', $limit, 't.user_id');
        $userlist = array();
        if (count($templist) > 0) {
            foreach ($templist as $user) {
                array_push($userlist, $user['user_id']);
            }
        }
        return $userlist;
    }

    /**
     * 昨天有竞猜过 今天未竞猜的弹出提示
     * @param $db
     * @param $ubeg 用户开始
     * @param $uend 用户结束
     */
    private static function setMsgJob($db, $userlist)
    {

        //昨天有竞猜过 今天未竞猜的弹出提示
        $beg = FinanceUtil::lastTradeDayTime() - 32400;
        $now = time();
        $guesslist = $db->whereIn('user_id', $userlist)
            ->whereBetween('createtime', [$beg, $now])
            ->groupBy('user_id')
            ->orderBy('user_id')
            ->get(DataTable::GUESS_TABLE, null, 'user_id,count(1) as count');
        echo($db->getLastQuery() . PHP_EOL);
        $templist = array();
        foreach ($guesslist as $item) {
            //必需积分大于85积分
            if ($item['count'] < 2) {
                $tempuser = $db->where('id', $item['user_id'])
                    ->where('score', 84, '>')
                    ->count(DataTable::USER_TABLE);
                if ($tempuser > 0) {
                    array_push($templist, $item['user_id']);
                }
            }
        }

        if (count($templist) > 0) {
            $list = $db->whereIn('user_id', $templist)
                ->get(DataTable::THIRD_TABLE, null, 'openid,openname');
            if (count($list) > 0) {
                echo('发送类型' . QueueType::MESSAGE_APPOINTMEMT_1 . ':' . count($list) . '条' . PHP_EOL);
                $job = new Job();
                $data['list'] = $list;
                $data['type'] = QueueType::MESSAGE_APPOINTMEMT_1;
                $job->setJobData($data);
                Queue::getInstance()->producer()->push($job);
            }
        }
    }

    /**
     * 通知所有人
     */
    private static function setAllJob($db, $userlist)
    {
        $list = $db->whereIn('user_id', $userlist)
            ->get(DataTable::THIRD_TABLE, null, 'openid,openname');


        if (count($list) > 0) {
            echo('发送类型' . QueueType::MESSAGE_APPOINTMEMT_1 . ':' . count($list) . '条' . PHP_EOL);
            $job = new Job();
            $data['list'] = $list;
            $data['type'] = QueueType::MESSAGE_APPOINTMEMT_1;
            $job->setJobData($data);
            Queue::getInstance()->producer()->push($job);
        }

    }

    public static function setTestJob()
    {
        $db = MysqlPool::defer();
        $list = $db->rawQuery("SELECT t.`user_id` ,t.`openid` ,t.`openname`  from `cz_third` as t LEFT JOIN `cz_user` as u on u.id = t.`user_id`  where t.`is_follow` = 1 and u.`status` != 'hidden' and t.`user_id` NOT in( select `user_id`  from `cz_finance_guess` WHERE `date_str` = '20191008')");
        /*
        foreach ($list as $item){
            $user = $db->where('id',$item['user_id'])->getOne(DataTable::USER_TABLE);
            $score = 100 - $user['score'];
            if($score >0){
                //加积分
                User::score($db,$score,$user['id'],'不够积分预测，赠送积分');
            }
        }*/

        if (count($list) > 0) {
            echo('发送类型' . QueueType::MESSAGE_APPOINTMEMT_3 . ':' . count($list) . '条' . PHP_EOL);
            $job = new Job();
            $data['list'] = $list;
            $data['type'] = QueueType::MESSAGE_APPOINTMEMT_3;
            $job->setJobData($data);
            Queue::getInstance()->producer()->push($job);
        }

    }

    /**
     * 上周竞猜过 这周没竞猜过的
     * @param $db
     * @param $limit
     */
    private static function setMsg2Job($db, $userlist)
    {
        $now = time();

        $lastweek = $now - 604800;
        $lastlastweek = $lastweek - 604800;
        $templist = array();

        $guesslist = $db->whereIn('user_id', $userlist)
            ->whereBetween('createtime', [$lastlastweek, $lastweek])
            ->groupBy('user_id')
            ->orderBy('user_id')
            ->get(DataTable::GUESS_TABLE, null, 'user_id,count(1) as count');

        foreach ($guesslist as $item) {
            if ($item['count'] > 0) {
                $guesslist2 = $db->where('user_id', $item['user_id'])
                    ->whereBetween('createtime', [$lastweek, $now])
                    ->count(DataTable::GUESS_TABLE);
                if ($guesslist2 < 1) {
                    array_push($templist, $item['user_id']);

                }

            }
        }
        if (count($templist) > 0) {
            $list = $db->whereIn('user_id', $templist)
                ->get(DataTable::THIRD_TABLE, null, 'openid,openname');
            if (count($list) > 0) {
                echo('发送类型' . QueueType::MESSAGE_APPOINTMEMT_2 . ':' . count($list) . '条' . PHP_EOL);
                $job = new Job();
                $data['list'] = $list;
                $data['type'] = QueueType::MESSAGE_APPOINTMEMT_2;
                $job->setJobData($data);
                Queue::getInstance()->producer()->push($job);
            }
        }
    }

    /**
     * 新加进入来的没有竞猜过的 很久没有竞猜的用户
     * @param $db
     * @param $limit
     */
    private static function setMsg3Job($db, $userlist)
    {
        $templist = array();
        $guesslist = $db->whereIn('user_id', $userlist)
            ->groupBy('user_id')
            ->orderBy('user_id')
            ->get(DataTable::GUESS_TABLE, null, 'user_id,count(1) as count');

        foreach ($guesslist as $item) {
            if ($item['count'] < 0) {
                array_push($templist, $item['user_id']);
            }
        }
        if (count($templist) > 0) {
            $list = $db->whereIn('user_id', $templist)
                ->get(DataTable::THIRD_TABLE, null, 'openid,openname');
            if (count($list) > 0) {
                echo('发送类型' . QueueType::MESSAGE_APPOINTMEMT_3 . ':' . count($list) . '条' . PHP_EOL);
                $job = new Job();
                $data['list'] = $list;
                $data['type'] = QueueType::MESSAGE_APPOINTMEMT_3;
                $job->setJobData($data);
                Queue::getInstance()->producer()->push($job);
            }
        }
    }

    /**
     * 很久没分竞猜
     * @param $db
     * @param $limit
     */
    private static function setMsg4Job($db, $userlist)
    {

        $lasttime = time() - 2592000;


        $templist = array();
        $userlist = $db->whereIn('id', $userlist)
            ->where('status', 'normal')
            ->get(DataTable::USER_TABLE, null, 'id,score');
        foreach ($userlist as $item) {
            $count = $db->where('user_id', $item['id'])
                ->where('createtime', $lasttime, '>')
                ->count(DataTable::GUESS_TABLE);
            if ($count <= 0) {
                $score = 100 - $userlist['score'];
                if ($score > 0) {
                    //加积分
                    User::score($db, $score, $item['id'], '不够积分预测，赠送积分');
                }
                array_push($templist, $item['id']);
            }
        }

        if (count($templist) > 0) {
            $list = $db->whereIn('user_id', $templist)
                ->get(DataTable::THIRD_TABLE, null, 'openid,openname');
            if (count($list) > 0) {
                echo('发送类型' . QueueType::MESSAGE_APPOINTMEMT_4 . ':' . count($list) . '条' . PHP_EOL);
                $job = new Job();
                $data['list'] = $list;
                $data['type'] = QueueType::MESSAGE_APPOINTMEMT_4;
                $job->setJobData($data);
                Queue::getInstance()->producer()->push($job);
            }
        }
    }


    /*预约功能，暂时不用
    static function run(\swoole_server $server, int $taskId, int $fromWorkerId,$flags=null)
    {
        $db = MysqlPool::defer();
        $h = int(date("H"));
        if($h === 8){
            //查询要推送的人哦
            //查询有多少人
            //分成四组  四个进程推送
            $page_size = 100;
            $count = $db->where('msg_status',1,'=')->count(DataTable::THIRD_TABLE);
            $pages = (int)$count/$page_size;
            if($pages < 1){
                echo('发送第一条推送哦'.PHP_EOL);
                $list = $db->where('msg_status',1,'=')->get(DataTable::THIRD_TABLE,null,'openid,openname');
                //添加一个JOB哦
                self::setJob($list,self::$MESSAGE_APPOINTMEMT);
            }else{

                for ($page=0;$page < $pages-1; $page++){
                    echo('第'.$page);
                    $list = $db->where('msg_status',1,'=')->get(DataTable::THIRD_TABLE,[$page*$page_size,$page_size],'openid,openname');
                    //添加一个JOB
                    self::setJob($list,self::$MESSAGE_APPOINTMEMT);
                }
                //取余数
                $mod = $count%$page_size;
                echo('余数'.$mod.PHP_EOL);
                if($mod > 0){
                    $list = $db->where('msg_status',1,'=')->get(DataTable::THIRD_TABLE,[$count-$mod,$mod],'openid,openname');
                    self::setJob($list,self::$MESSAGE_APPOINTMEMT);
                }
            }
        }
        if(($h >= 0 && $h<8)||($h >= 16 && $h < 20)){
            //是否发送竞猜中通知
        }
    }
    */

    public static function testsend()
    {
        $wechat = new Wechat();
        $client = $wechat->GetClient();

        $data['first']['value'] = '尊敬的，你昨天参与的大盘猜涨跌活动要开始了，赶紧来预测吧，10万现金红包等着你！';
        $data['keyword1']['value'] = '20190926';
        $data['keyword2']['value'] = '上证先知道——大盘猜涨跌活动';
        $data['remark']['value'] = '点击进入，立马预测涨跌';
        $tempmsg = new TemplateMsg();
        $tempmsg->setTemplateId('1JsOd96YOAzUOXpl5SXxw8ivT3-Z9ixLCf38OY7-jqs');
        $tempmsg->setTouser('oRyB6uFfFcxZiUMfFIlBr9AVfPdI');
        $tempmsg->setData($data);
        $tempmsg->setUrl(CacheTable::getFinanceConfig()['HOST_URL']);
        try {
            $client->officialAccount()->templateMsg()->send($tempmsg);
        } catch (\Exception $e) {

        }

    }

    public static function consumer($list)
    {
        $wechat = new Wechat();
        $client = $wechat->GetClient();

        $date_str = date("Y/m/d");
        foreach ($list as $msg) {

            $data['first']['value'] = '尊敬的' . $msg['openname'] . '，你昨天参与的大盘猜涨跌活动要开始了，赶紧来预测吧';
            $data['keyword1']['value'] = $date_str;
            $data['keyword2']['value'] = '上证先知道——大盘猜涨跌活动';
            $data['remark']['value'] = '点击进入，立马预测涨跌';
            $tempmsg = new TemplateMsg();
            $tempmsg->setTemplateId('1JsOd96YOAzUOXpl5SXxw8ivT3-Z9ixLCf38OY7-jqs');
            $tempmsg->setTouser($msg['openid']);
            $tempmsg->setData($data);
            $tempmsg->setUrl(CacheTable::getFinanceConfig()['HOST_URL']);
            try {
                $client->officialAccount()->templateMsg()->send($tempmsg);
            } catch (\Exception $e) {
                continue;
            }

        }

    }

    public static function consumer2($list)
    {
        $wechat = new Wechat();
        $client = $wechat->GetClient();

        $date_str = date("Y/m/d");
        foreach ($list as $msg) {

            $data['first']['value'] = '尊敬的' . $msg['openname'] . '，上周你没有预测正确，这周要加油哦，听说大神门都猜涨！';
            $data['keyword1']['value'] = $date_str;
            $data['keyword2']['value'] = '上证先知道——大盘猜涨跌活动';
            $data['remark']['value'] = '点击进入，立马预测涨跌';
            $tempmsg = new TemplateMsg();
            $tempmsg->setTemplateId('1JsOd96YOAzUOXpl5SXxw8ivT3-Z9ixLCf38OY7-jqs');
            $tempmsg->setTouser($msg['openid']);
            $tempmsg->setData($data);
            $tempmsg->setUrl(CacheTable::getFinanceConfig()['HOST_URL']);
            try {
                $client->officialAccount()->templateMsg()->send($tempmsg);
            } catch (\Exception $e) {
                continue;
            }

        }

    }

    public static function consumer3($list)
    {
        $wechat = new Wechat();
        $client = $wechat->GetClient();

        $date_str = date("Y/m/d");
        foreach ($list as $msg) {

            $data['first']['value'] = '尊敬的' . $msg['openname'] . '，你的积分都铺满灰了，赶快前来预测涨跌吧，礼品都在等你呢！';
            $data['keyword1']['value'] = $date_str;
            $data['keyword2']['value'] = '上证先知道——大盘猜涨跌活动';
            $data['remark']['value'] = '点击进入，立马预测涨跌';
            $tempmsg = new TemplateMsg();
            $tempmsg->setTemplateId('1JsOd96YOAzUOXpl5SXxw8ivT3-Z9ixLCf38OY7-jqs');
            $tempmsg->setTouser($msg['openid']);
            $tempmsg->setData($data);
            $tempmsg->setUrl(CacheTable::getFinanceConfig()['HOST_URL']);
            try {
                $client->officialAccount()->templateMsg()->send($tempmsg);
            } catch (\Exception $e) {
                continue;
            }

        }
    }

    public static function consumer4($list)
    {
        $wechat = new Wechat();
        $client = $wechat->GetClient();

        $date_str = date("Y/m/d");
        foreach ($list as $msg) {
            $data['first']['value'] = '尊敬的' . $msg['openname'] . '，听说你不够积分预测了，不要紧，这里有100积分，赶快去竞猜吧！';
            $data['keyword1']['value'] = $date_str;
            $data['keyword2']['value'] = '上证先知道——大盘猜涨跌活动';
            $data['remark']['value'] = '点击进入，立马预测涨跌';
            $tempmsg = new TemplateMsg();
            $tempmsg->setTemplateId('1JsOd96YOAzUOXpl5SXxw8ivT3-Z9ixLCf38OY7-jqs');
            $tempmsg->setTouser($msg['openid']);
            $tempmsg->setData($data);
            $tempmsg->setUrl(CacheTable::getFinanceConfig()['HOST_URL']);
            try {
                $client->officialAccount()->templateMsg()->send($tempmsg);
            } catch (\Exception $e) {
                continue;
            }
        }

    }

}